package com.kjj.org.service.impl;

import com.kjj.basic.constants.BaseConstants;
import com.kjj.basic.service.IBaiduAiService;
import com.kjj.basic.util.AjaxResult;
import com.kjj.basic.util.RedisUtils;
import com.kjj.org.domain.Employee;
import com.kjj.org.domain.Shop;
import com.kjj.org.domain.ShopAuditLog;
import com.kjj.org.mapper.EmployeeMapper;
import com.kjj.org.mapper.ShopAuditLogMapper;
import com.kjj.org.mapper.ShopMapper;
import com.kjj.org.service.IEmployeeService;
import com.kjj.org.service.IShopService;
import com.kjj.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kan
 * @since 2022-09-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IBaiduAiService baiduAiService;
    @Autowired
    private ShopAuditLogMapper logMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private IEmployeeService employeeService;
    @Override
    @Transactional
    public void settlement(Shop shop) {
        //1.校验
        //空校验
        validate(shop);
        //
        //2.保存店铺信息
        shop.setRegisterTime(new Date());
        shopMapper.save(shop);
        //3.保存店铺管理员信息 但是如果店铺管理员原来就有店铺
        //方案一 直接使用原来的店铺管理员信息
        Employee admin = shop.getAdmin();
        String username = admin.getUsername();
        Employee adminByDb = employeeMapper.loadByUsername(username);
        if (adminByDb == null) {
//            admin.setShopId(shop.getId());
            admin.setState(BaseConstants.Employee.STATE_LOGOUT);
            employeeService.add(admin);
        }
        //方案二 不让入驻 直接登录

        //4.设置管理员
        shop.setAdminId(adminByDb==null?admin.getId():adminByDb.getId());

        //进行自动审核
        String authText = shop.getName() + "" + shop.getAddress();
        System.out.println(authText);
        AjaxResult ajaxResult = baiduAiService.audit(authText, null, null);
        ShopAuditLog auditLog = new ShopAuditLog();
        auditLog.setState(ajaxResult.isSuccess() ? 2 : 4);
        auditLog.setShopId(shop.getId());
        auditLog.setAuditTime(new Date());
        auditLog.setNote(ajaxResult.isSuccess() ? "审核通过" : "失败"+ajaxResult.getMessage());
        if (ajaxResult.isSuccess()) {
            shop.setState(BaseConstants.Shop.STATE_WAIT_ACTIVE);
        }else {
            shop.setState(BaseConstants.Shop.STATE_REJECT_AUDIT);
        }
        shopMapper.update(shop);
        logMapper.save(auditLog);

    }

    @Override
    public void check(Shop shop) {
        shopMapper.checkState(shop);
    }

    @Override
    public void sendMessage(Long id, String UUID) throws Exception {
        System.out.println(id);
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("1825799522@qq.com");
        helper.setSubject("邮件测试.......");
        http://img30.360buyimg.com/popWaterMark/jfs/t1/67988/7/14094/232759/5db64acfE6ab2b09e/38b5cb3dc38b4b1f.jpg"
        helper.setText("<a href='http://localhost/shop/activate/"+id+"/"+UUID+"'>激活</a><br><h1>邮件测试</h1>"+
                "<img src='https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2022%2F0105%2F0a885be3j00r57sju003gd000tw01g0m.jpg&thumbnail=660x2147483647&quality=80&type=jpg\'/>",true);
        //添加附件
        helper.addAttachment("旗袍姐姐.jpg",new File("C:\\Users\\Administrator\\Desktop\\img\\qipao.jpg"));
        helper.addAttachment("旗袍姐姐2.jpg",new File("C:\\Users\\Administrator\\Desktop\\img\\1.jpg"));
        helper.addAttachment("旗袍姐姐3.jpg",new File("C:\\Users\\Administrator\\Desktop\\img\\2.jpg"));
        helper.addAttachment("压缩文件", new File("C:\\Users\\Administrator\\Desktop\\redis-5.0.14.tar.gz"));
        //收件人
        helper.setTo("k15184401775@163.com");
        javaMailSender.send(mimeMessage);
    }

    @Override
    public String getUUID() {
        Jedis jedis = RedisUtils.INSTANCE.getSource();
        String token = UUID.randomUUID().toString();
        // NX是不存在时才set， XX是存在时才set， EX是秒，PX是毫秒
//        jedis.set("UUID",token,"NX","EX",60*60);
        jedis.setex("UUID", 60 * 60,token);
        RedisUtils.INSTANCE.closeSource(jedis);
        return token;
    }

    @Override
    public Boolean checkUUID(String uuid) {
        Jedis jedis = RedisUtils.INSTANCE.getSource();
        String UUID_REDIS = jedis.get("UUID");
        System.out.println(UUID_REDIS);
        if (UUID_REDIS!=null && UUID_REDIS.equals(uuid)){
            return true;
        }
        return false;
    }

    private void validate(Shop shop) {
        //1.1 null检验
        if (shop==null)
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        if (StringUtils.isEmpty(shop.getName()))
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        if (shop.getAdmin()==null)
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        if (StringUtils.isEmpty(shop.getAdmin().getUsername())||
                StringUtils.isEmpty(shop.getAdmin().getPassword())|| StringUtils.isEmpty(shop.getAdmin().getComfirmPassword()))
        {
            System.out.println(shop.getAdmin());
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        }
        //1.2 两次密码比对
        if (!shop.getAdmin().getPassword().trim().equals(shop.getAdmin().getComfirmPassword().trim()))
            throw new RuntimeException("两次密码不一致");

        //1.3 店铺是否存在
        Shop shopByDb = shopMapper.loadByName(shop.getName());
        if (shopByDb!=null)
            throw new RuntimeException("该店铺已经存在！");
    }

}
